<?php
/**
 * @user:andy
 * @date:2021/8/1
 * @company:http://www.sjdphp.com
 * @desc:
 */

namespace app\admin\controller;


use app\common\controller\BackBaseController;
use app\common\server\Json;
use app\common\server\Tree;

class Boroughs extends BackBaseController
{
    protected $model_id = 'boroughs_id';
    protected $model_name = 'boroughs_name';
    protected $model_status = 'boroughs_status';


    public function add(){
        if($this->request->isPost()){
            $param = $this->request->param();
            ## 校验参数
            $validate = self::getBusExample($this->request->controller(),2);
            if(!$validate->scene("add")->check($param)) return Json::error($validate->getError());

            ## 默认状态
            $param[$this->model_status] = config("project.mysql_code.table_pending");

            ## 数据入库
            $class = self::getBusExample($this->request->controller());
            $res = $class::insertOrUpdateAndDel($param);

            return $res;
        }else{
            return view("",[
                'bors' => $this->getBoroughsLists()
            ]);
        }
    }

    public function edit(){
        if($this->request->isPost()){
            $param = $this->request->param();

            ## 校验参数
            $validate = self::getBusExample($this->request->controller(),2);
            if(!$validate->scene("edit")->check($param)) return Json::error($validate->getError());

            ## 数据入库
            $class = self::getBusExample($this->request->controller());
            $res = $class::insertOrUpdateAndDel($param,2);

            return $res;
        }else{
            $boroughs_id = $this->request->param("boroughs_id",0,'intval');
            if(!empty($boroughs_id)){
                $class = self::getBusExample($this->request->controller());
                $info = $class::getInfo(array($this->model_id => $boroughs_id));
            }
            return view('',[
                'info'   => $info,
                'bors' => $this->getBoroughsLists(),
            ]);
        }
    }

    /** 获取对应的行政数据
     * @return array
     * @throws \ReflectionException
     */
    public function getBoroughsLists(){
        $term= [
            ['boroughs_status','=',config("project.mysql_code.table_normal")]
        ];
        if($this->request->isPost()){ ## 判断是否为异步请求
            $pid = $this->request->param("pid",0,'intval');
            $term[] = ['pid','=',$pid];
        }

        $class = self::getBusExample($this->request->controller());
        $lists = $class::getArrayLists($term,'boroughs_id,boroughs_name,pid');

        return Tree::getBoroughsLists($lists);
    }
}